<template>
  <div class="product-details">
    <van-nav-bar fixed title="商品详情" left-arrow @click-left="goBack" />
    <van-list class="item-list">
      <van-swipe-cell v-for="item in items" :key="item.itemId" class="item" inset>
        <van-card
            :price="item.listPrice"
            :desc="item.attribute1"
            :title="item.itemId"
            :num="item.quantity"
            :thumb="showProduct.img"
            style="border-radius: 3ch;"
        >
          <template #footer>
            <div class="item-actions">
              <van-stepper v-model="item.quantity" theme="round" button-size="22" min="1" :max="item.maxQuantity" disable-input @click.stop/>
              <van-button round @click="addToCart(item)" color="#FFDF75" style="height:40px; font-weight:700;">加入购物车</van-button>
            </div>
          </template>
        </van-card>
      </van-swipe-cell>
      <van-empty v-if="items.length === 0" description="无商品" />
    </van-list>
  </div>
  <!-- 跳转购物车按钮 -->
  <van-button
      round
      color="#FFAC00"
      style="position: fixed; right: 20px; bottom:70px; z-index: 999; opacity: 70%; user-select: none;"
      @click="goCart"
  >
    <van-icon name="shopping-cart-o" slot="right" />
  </van-button>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { showToast } from 'vant';
import { allProductListService, itemsByProductService } from "@/api/category.js";
import { addCartItemService } from "@/api/cart.js";
import router from "@/router/index.js";

const route = useRoute();
const productID = route.params.id;


// 商品项目列表
const items = ref([]);

//从后端接收到的Pro列表
const products = ref([]);

//转换从后端接收到的Pro列表
const showProducts = ref([]);

//某商品详细信息
const showProduct = ref({
  id: 0,
  productId: "",
  categoryId: "",
  name: "",
  img: '',
  description: ""
});

// 获取所有商品项目信息
const fetchItems = async () => {
  try {
    const result = await itemsByProductService(productID);
    items.value = result.data.data.map(item => ({
      ...item,
      img: 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg', // 默认图片
      maxQuantity: item.quantity,
      quantity: 1
    }));
  } catch (error) {
    console.error('获取商品项目信息失败', error);
  }
};

// 添加到购物车
const addToCart = async (item) => {
  try {
    await addCartItemService(item.itemId, item.quantity);
    showToast({
          message: `<div style="height:22px;display:flex;justify-content: center;align-items: center;user-select:none;"><i class="van-icon van-icon-success" style="font-size:16px;margin-right:5px"></i><span>加入购物车成功</span></div>`,
          type: 'html'
        });
  } catch (error) {
    showToast({
          message: `<div style="height:22px;display:flex;justify-content: center;align-items: center;user-select:none;"><i class="van-icon van-icon-fail" style="font-size:16px;margin-right:5px"></i><span>加入购物车失败</span></div>`,
          type: 'html'
        });
    console.error('加入购物车失败', error);
  }
};

// 转换函数
const changeProducts = () => {
  products.value.forEach(product => {
    let str = product.description;
    const urlRegex = /src="([^"]+)"/;
    const urlMatch = str.match(urlRegex);
    let url = urlMatch ? urlMatch[1] : 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg';
    const indexGreaterThan = str.indexOf('>');
    const sentence = indexGreaterThan !== -1 ? str.substring(indexGreaterThan + 1) : '';
    product.img = url;
    product.description = sentence;
  });
  console.log('转换完成');
};


// 获取所有商品列表并处理
const allProductList = async () => {
  try {
    const result = await allProductListService();
    products.value = result.data.data;
    console.log('products get');
    changeProducts();
    productDetail();
    console.log(showProduct.value.productId);
  } catch (error) {
    console.error('获取商品列表失败', error);
  }
};

// 设置当前商品详细信息
const productDetail = () => {
  showProduct.value = products.value.find(product => product.id.toString() === productID) || {
    id: 1,
    productId: "1",
    categoryId: "1",
    name: "1",
    img: '',
    description: ""
  };
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};
const goCart = () => { 
  router.push('/cart');
}

onMounted(() => {
  allProductList();
  fetchItems();
});
</script>


<style scoped>
.product-details {
  padding: 15px;
  user-select: none;
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
}

.product-info {
  margin-bottom: 20px;
}

.product-image {
  width: 100%;
  height: auto;
}

.product-items {
  margin-top: 20px;
}

.item-list {
  padding-bottom: 20%;
  margin-top: 12%;
}
.item-image {
  width: 100%;
  height: auto;
}

.item-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item {
  padding: 16px; /* 内边距 */
  border-bottom: 1px solid #ebedf0; /* 底部边框 */
  height: 50%;
  background-color: white;
}
.van-nav-bar {
  background-color: #FFDF75;
}
.van-stepper {
  margin-top: 8px;
  --van-stepper-button-round-theme-color: #FFDF75;
}
</style>




